﻿namespace Ruirun.Mes.Extensions
{
    public static class ConfigurationExtension
    {
        /// <summary>
        /// 从<see cref="IConfiguration"/>创建<see cref="ProjectOptions"/>
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static ProjectOptions GetDemoOptions(this IConfiguration configuration)
        {
            var options = configuration.GetOptions<ProjectOptions>("Project", (conf, key) =>
            {
                IConfigurationSection section = configuration.GetSection(key);
                if (!section.Exists())
                {
                    throw new MicroCloudException("Project配置选项不存在，请在appsetting.json配置 Project 节点");
                }

                var opts = new ProjectOptions();
                opts.DemoString = configuration["Project:DemoString"] ?? "Default value";
                opts.DemoInt32 = configuration["Project:DemoInt32"].CastTo(0);
                opts.DemoBoolean = configuration["Project:DemoBoolean"].CastTo(false);

                var demoStringArrayStr = configuration["Project:DemoStringArray"];
                opts.DemoStringArray = demoStringArrayStr == null || demoStringArrayStr == "*" ? Array.Empty<string>() : demoStringArrayStr.Split(',');

                var demoListSection = configuration.GetSection("Project:DemoList");
                opts.DemoItems = demoListSection.Get<IEnumerable<OptionItem>>();
                return opts;
            });

            return options;
        }
    }
}
